﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using SubSonic;
using Business;

public partial class User_Employer_RegisterContract : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            Lblstatus.CssClass = "MainObject";
            Lblstatus.Text = "";

            if (!IsPostBack)
            {

                string year = (DateTime.Now.Year - 621).ToString();

                TxtYear.Text = year;
                //PersianCalendar1.SelectedDate = DateTime.Now;
                DataTable dt = new DataTable();

                DataColumn myDataColumn;

                myDataColumn = new DataColumn();
                myDataColumn.DataType = Type.GetType("System.String");
                myDataColumn.ColumnName = "ID";
                dt.Columns.Add(myDataColumn);

                myDataColumn = new DataColumn();
                myDataColumn.DataType = Type.GetType("System.String");
                myDataColumn.ColumnName = "Name";
                dt.Columns.Add(myDataColumn);


                Session["Village"] = dt;
                //DropDownAdvisor.DataSource = Roles.GetUsersInRole("Advisor");
                //DropDownAdvisor.DataBind();
                IDataReader dr = DataAccess.TblUserDetail.FetchByParameter(DataAccess.TblUserDetail.Columns.Role, "FourthFactor");
                while (dr.Read())
                {
                    ListItem l = new ListItem();
                    l.Text = dr["Name"].ToString() + " " + dr["Family"].ToString();
                    l.Value = dr["UserId"].ToString();
                    DropDownListFourthFactor.Items.Add(l);
                    DropDownListFourthFactor.DataBind();
                }
                dr.Close();
                DropDownListFourthFactor.Items[0].Selected = true;
            }
        }
        catch
        {
            Lblstatus.CssClass = "error";
            Lblstatus.Text = "خطا در بارگذاری صفحه";
            

        }
    }
    //protected void DropDownAdvisor_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    ProfileCommon p = Profile.GetProfile(DropDownAdvisor.SelectedItem.Text);
    //    //Lbladdress.Text = p.Contacts.Address;
    //    //LblName.Text = p.Common.FirstName + " " + p.Common.LastName + " " + p.HoghooghiAdvisor.Manager;
    //    //LblTel.Text = p.Contacts.Phone1;
    //    //LblMobile.Text = p.Contacts.Mobile;

    //}
    protected void ListVillages_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void LinkButtonInsert_Click(object sender, EventArgs e)
    {
        try
        {
            if (DropDownVillage.SelectedValue != "")
            {
                //DropDownList dp = (DropDownList)SelectCity1.FindControl("DropDownListVillage");
                DataTable dt = (DataTable)Session["Village"];
                DataRow row;
                row = dt.NewRow();
                row["ID"] = DropDownVillage.SelectedItem.Value;
                row["Name"] = DropDownVillage.SelectedItem.Text;
                dt.Rows.Add(row);
                filllist();
                Session["Village"] = dt;
                Lblstatus.CssClass = "";
                // ListVillages.Items.Add( dp.SelectedItem.Text);
                //ListVillages.DataBind();
            }
            else
                Lblstatus.Text = " روستا بایستی انتخاب شود";
            Lblstatus.CssClass = "error";
        }
        catch
        {
            Lblstatus.Text = "خطا در لیست روستاها";
            Lblstatus.CssClass = "error";
        }

    }

    public void filllist()
    {
        DataTable dt = (DataTable)Session["Village"];
        ListVillages.DataSource = dt;
        ListVillages.DataTextField = "Name";
        ListVillages.DataValueField = "ID";
        ListVillages.DataBind();
    }
    
    protected void LinkButtonDelete_Click(object sender, EventArgs e)
    {
        if (ListVillages.Items.Count == 0)
        {
            Lblstatus.Text = ".لیست خالی میباشد";
            Lblstatus.CssClass = "error";
        }
        if (ListVillages.Items.Count > 0)
        {
            if (ListVillages.SelectedIndex >= 0)
            {
                DataTable dt = (DataTable)Session["Village"];
                dt.Rows.RemoveAt(ListVillages.SelectedIndex);
                Session["Village"] = dt;
                filllist();
            }
            else
            {
                Lblstatus.Text = ".لطفا ابتدا روستا را انتخاب بفرمایید ";
                Lblstatus.CssClass = "error";
            }
        }


    }
    public void clear()
    {
        DataTable dt = (DataTable)Session["Village"];
        dt.Clear();
        Session["Village"] = dt;
        filllist();
        TxtContractNumber.Text = String.Empty;
        //JQDatePicker1.Text = "";
        TextBoxDate.Text = String.Empty;
        DropDownCity.ClearSelection();
        GridViewVillageDetail.DataSource = String.Empty;
        GridViewVillageDetail.DataBind();
        //Lbladdress.Text = "";
        //LblMobile.Text = "";
        //LblName.Text = "";
        //LblTel.Text = "";
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = (DataTable)Session["Village"];
            if(dt.Rows.Count>0)
          {
            for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                DataAccess.TblContract contract = new DataAccess.TblContract();
                contract.VillageId = new Guid(dt.Rows[i]["ID"].ToString());
                //string s = Request.Form["txtDate"].ToString();
                //string s =JQDatePicker1.Text;
                string s = TextBoxDate.Text;
                string[] split = s.Split(new Char[] { '/' });
                Business.Calender calender = new Business.Calender();
                DateTime Date = calender.PersianToMiladi(split[0].ToString(), split[1].ToString(), split[2].ToString());
                //MembershipUser mu= Membership.GetUser(DropDownAdvisor.SelectedItem.Text);
                contract.UserId = (Guid)Session["UserId"];
                contract.AdvisorName = LblNameFamily.Text;
                contract.ContractDate = Date;
                contract.Year = Convert.ToInt32( TxtYear.Text);
                contract.FourthFactorUserId =new Guid( DropDownListFourthFactor.SelectedItem.Value);
                //contract.AdvisorName = DropDownAdvisor.SelectedItem.Text;
                contract.ContractNumber = TxtContractNumber.Text;
                if (RadioButtonListRole.SelectedItem.Value == "Advisor")
                {
                    contract.ContractType = true;
                    contract.Save();
                    object pk= contract.GetPrimaryKeyValue();
                    Tasksinsert(pk);
                }
                if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
                {
                    contract.ContractType = false;
                    contract.Save();
                   object pk= contract.GetPrimaryKeyValue();
                   Tasksinsert(pk);
                }
            }
                
            
            Lblstatus.CssClass = "success";
            Lblstatus.Text = " .قرارداد با موفقیت ثبت گردید ";
            
            clear(); 
               
          }
            else
            {
                   Lblstatus.Text = " .روستاهای مورد قرارداد را انتخاب کنید ";
                   Lblstatus.CssClass = "error";
            }
          
        }
        catch
        {
            Lblstatus.Text = " .ثبت قرارداد باخطا مواجه شد ";
            Lblstatus.CssClass = "error";
 
        }
    }
    public void Tasksinsert(object contractid)
    {
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            for (int j = 1; j <= 18; j++)
            {
                DataAccess.TblTask t = new DataAccess.TblTask();

                IDataReader dr = DataAccess.TblStepsAdvisor.FetchByParameter(DataAccess.TblStepsAdvisor.Columns.Priority, j);
                dr.Read();
                Guid drToString = new Guid(dr["ID"].ToString());
                t.AdvisorStepId = drToString;
                dr.Close();
                t.ContractId = (Guid)contractid;
                t.IsDonei = false;
                t.UserName = Membership.GetUser().UserName;
                
                t.Save();
            }
        }
        if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
        {
            for (int j = 1; j <= 8; j++)
            {
                DataAccess.TblTask t = new DataAccess.TblTask();

                IDataReader dr = DataAccess.TblStepsSurveyor.FetchByParameter(DataAccess.TblStepsSurveyor.Columns.Priority, j);
                dr.Read();
                Guid drToString = new Guid(dr["ID"].ToString());
                t.SurveyorStepId = drToString;
                dr.Close();
                t.ContractId = (Guid)contractid;
                t.IsDonei = false;
                t.UserName = Membership.GetUser().UserName;
              
                t.Save();
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        clear();
        cleargrid();
        MultiView1.ActiveViewIndex = 0;
    }
    protected void PersianCalendar1_SelectionChanged(object sender, EventArgs e)
    {
        PopupControlExtender1.Commit(PersianCalendar1.SelectedDatePersian);
    }


    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
       
    }
    public void cleargrid()
    {
        GridViewUsers.DataSource = null;
        GridViewUsers.DataBind();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            BindingGrid();
        }
        catch
        { }
    }

    private void BindingGrid()
    {
        string orderExpression = DataAccess.TblUserDetail.Columns.Name;
        SubSonic.Query tempQuery = new Query(DataAccess.TblUserDetail.Schema);
        tempQuery.OrderBy = SubSonic.OrderBy.Asc("Name");
        if (ViewState["SortExpression"] != null && !ViewState["SortExpression"].ToString().Trim().Equals(String.Empty))
        {
            switch (ViewState["SortExpression"].ToString())
            {
                case "Name":
                    orderExpression = DataAccess.TblUserDetail.Columns.Name;
                    break;
                case "Family":
                    orderExpression = DataAccess.TblUserDetail.Columns.Family;
                    break;
                case "UserName":
                    orderExpression = DataAccess.TblUserDetail.Columns.UserName;
                    break;
            }

            tempQuery.OrderBy = ViewState["SortDirection"] != "Ascending" ? SubSonic.OrderBy.Desc(orderExpression) : SubSonic.OrderBy.Asc(orderExpression);
        }
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            if (RadioButtonListAdvisors.SelectedItem.Value == "Advisorhoghooghi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhoghooghi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " .فرد مورد نظر یافت نشد ";
                    Lblstatus.CssClass = "error";
                    cleargrid();
                }
            }
            if (RadioButtonListAdvisors.SelectedItem.Value == "Advisorhaghighi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhaghighi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " .فرد مورد نظر یافت نشد ";
                    Lblstatus.CssClass = "error";
                    cleargrid();
                }
            }
        }
        if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
        {
            if (RadioButtonListSurveyor.SelectedItem.Value == "hoghooghi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhoghooghi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " .فرد مورد نظر یافت نشد ";
                    Lblstatus.CssClass = "error";
                    cleargrid();
                }
            }
            if (RadioButtonListSurveyor.SelectedItem.Value == "haghighi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhaghighi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " .فرد مورد نظر یافت نشد ";
                    Lblstatus.CssClass = "error";
                    cleargrid();
                }
            }
        }
    }

    protected void RadioButtonListRole_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            RadioButtonListAdvisors.Visible = true;
            RadioButtonListSurveyor.Visible = false;
        }
        else
        {
            RadioButtonListSurveyor.Visible = true;
            RadioButtonListAdvisors.Visible = false;
        }
    }
    protected void RadioButtonListAdvisors_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridViewUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName != "Sort")
        {
            try
            {
                int id = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName)
                {
                    case "Select":
                        Guid userid = new Guid(GridViewUsers.DataKeys[id].Value.ToString());
                        string NameFamily = GridViewUsers.Rows[id].Cells[0].Text + " , " +
                                            GridViewUsers.Rows[id].Cells[1].Text;
                        Session["UserId"] = userid;
                        MultiView1.ActiveViewIndex = 1;
                        LblNameFamily.Text = NameFamily;
                        break;
                }
            }

            catch
            {
            }
        }
    }
    protected void DropDownVillage_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GridViewVillageDetail.DataSource = DataAccess.TblVillage.FetchByParameter(DataAccess.TblVillage.Columns.Id, SubSonic.Comparison.Equals, DropDownVillage.SelectedItem.Value.ToString());

            GridViewVillageDetail.DataBind();
        }
        catch
        { 
        }
    }

    protected void GridViewUsers_OnSort(object sender, GridViewSortEventArgs e)
    {
        // get values from viewstate
        String sortExpression = ViewState["SortExpression"] as string;
        String sortDirection = ViewState["SortDirection"] as string;

        // on first time header clicked ( including different header), sort ASCENDING
        if (e.SortExpression != sortExpression)
        {
            sortExpression = e.SortExpression;
            sortDirection = "Ascending";
        }
        // on second time header clicked, toggle sort
        else
        {
            if (sortDirection == "Ascending")
            {
                sortExpression = e.SortExpression;
                sortDirection = "Descending";
            }
            // Descending
            else
            {
                sortExpression = e.SortExpression;
                sortDirection = "Ascending";
            }
        }

        // save state for next time

        ViewState["SortExpression"] = sortExpression;
        ViewState["SortDirection"] = sortDirection;
        BindingGrid();
    }

}
